package reflect;

import java.lang.reflect.Field;

/**
 * 使用反射机制操作属性
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws Exception {
        Teacher t = new Teacher();
        t.name = "张三";//开发中几乎不这样做，都是用set方法设置:t.setName("张三");
        t.age = 34;
        System.out.println(t);

        Class cls = Class.forName("reflect.Teacher");
        Object obj = cls.newInstance();
        /*
            Field 属性对象，该类的每一个实例用于表示一个属性
         */
        Field field = cls.getField("name");
        field.set(obj,"李四");//obj.name = "张三";
        System.out.println(obj);

        Field field1 = cls.getField("age");
        field1.set(obj,22);
        System.out.println(obj);

        Object value1 = field.get(obj);//String name = obj.name;
        Object value2 = field1.get(obj);//int age = obj.age;
        System.out.println(value1);
        System.out.println(value2);
    }
}


